package com.fashion.schedule;

import com.fashion.utils.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * User: gnyk
 * Date: 13-2-18
 */
public class ScheduledPageSaver {
    private List<HtmlMapper> htmlMappers;
    /*  private URL url;
  private String fileName;*/
    private static final Logger logger = Logger.getLogger(ScheduledPageSaver.class);
    private String persistentFolder;

    protected void saveHtmlList() {
        for (HtmlMapper htmlMapper : htmlMappers) {
            logger.info("start to save index html: " + htmlMapper.getFileName());
            saveOneHtml(htmlMapper);
        }
    }

    protected void saveOneHtml(HtmlMapper htmlMapper) {
        try {
            String savedFileName = persistentFolder + File.separator + htmlMapper.getFileName();
            deletedOldHtml(savedFileName);

            URL url = new URL(htmlMapper.getUrl());
            AtomicReference<InputStream> is = new AtomicReference<InputStream>();
            byte bytes[] = new byte[1024 * 1000];
            int index = 0;
            is.set(url.openStream());
            int count = is.get().read(bytes, index, 1024 * 100);

            while (count != -1) {
                index += count;
                count = is.get().read(bytes, index, 1);
            }

            FileOutputStream fos = new FileOutputStream(savedFileName);
            fos.write(bytes, 0, index);
            is.get().close();
            fos.close();
        } catch (IOException e) {
            logger.error("Can not save " + htmlMapper.getFileName() + " for url: " + htmlMapper.getUrl(), e);
        }
    }

    protected void deletedOldHtml(String savedFileName) {
        File savedFile = new File(savedFileName);
        if (savedFile.exists()) {
            int deleteTime = 0;
            while (!savedFile.delete() && deleteTime < 10) {
                deleteTime++;
                try {
                    Thread.sleep(6000);
                } catch (InterruptedException ignored) {

                }

                logger.error("Could not delete saved html file: " + savedFileName);
            }
        }
    }

    public void setPersistentFolder(String persistentFolder) {
        this.persistentFolder = persistentFolder;
    }

    public void setHtmlMappers(List<HtmlMapper> htmlMappers) {
        this.htmlMappers = htmlMappers;
    }
}
